import { Ref } from 'vue'
import {
  otherRelativeHeight,
  paginationRelativeHeight,
  queryFormRelativeHeight
} from '../constant'

export function useAutoHeight(
  props,
  queryFormInst: Ref,
  isFullscreen: Ref<boolean>
) {
  const tableMaxHeight = ref(0)

  const updateTableMaxHeight = () => {
    if (!props.autoHeight && !isFullscreen) return
    nextTick(() => {
      const styleType = props.styleType as any
      const bodyClientHeight = document.body.clientHeight
      const queryFormClientHeight =
        queryFormInst.value?.$el.clientHeight ||
        queryFormRelativeHeight[styleType]
      const paginationClientHeight = props.pagination
        ? 70
        : paginationRelativeHeight[styleType]

      const fullscreenHeight = isFullscreen.value ? 95 : 0
      const relativeHeight = isFullscreen.value
        ? props.fullscreenRelativeHeight
        : props.relativeHeight

      tableMaxHeight.value =
        bodyClientHeight -
        queryFormClientHeight -
        paginationClientHeight -
        otherRelativeHeight[styleType] +
        fullscreenHeight +
        relativeHeight
    })
  }

  // TODO: 这样写会导致初始的时候updateTableMaxHeight()会执行两次
  watch(
    [isFullscreen, queryFormInst],
    () => {
      if (props.autoHeight) {
        updateTableMaxHeight()
      }
    },
    { immediate: true }
  )

  onMounted(() => {
    window.addEventListener('resize', updateTableMaxHeight)
  })
  onUnmounted(() => {
    window.removeEventListener('resize', updateTableMaxHeight)
  })

  return {
    tableMaxHeight,
    updateTableMaxHeight
  }
}
